package leetcode;

import java.util.Stack;

/**
 * 155.最小栈
 * 设计一个支持 push ，pop ，top 操作，并能在常数时间内检索到最小元素的栈。时间复杂度为O(1)
 */

//双栈解决问题
class MinStack {

    //s1是实际存储元素的栈
    private Stack<Integer> s1 = new Stack<>();
    //s2是存储最小元素的栈
    private Stack<Integer> s2 = new Stack<>();
    private int size;

    public MinStack() {

    }

    public void push(int val) {
        s1.push(val);
        if(s2.isEmpty()){
            s2.push(val);
        }else{
            //比较val和当前s2栈顶元素的大小，让小的入栈
            s2.push(Math.min(val,s2.peek()));
        }
        size ++;
    }

    public void pop() {
        s1.pop();
        s2.pop();
        size --;
    }

    public int top() {
        return s1.peek();
    }

    public int getMin() {
        return s2.peek();
    }
}

public class Num_155 {
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(3);
        minStack.push(2);
        minStack.push(1);
        minStack.push(5);
        minStack.push(4);
        System.out.println("栈顶：" + minStack.top());
        System.out.println("最小值为：" + minStack.getMin());
    }
}
